import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { ProductCategory } from '../types/inventory';
import { toast } from 'sonner';

interface InventoryContextType {
  categories: ProductCategory[];
  addCategory: (name: string, initialStock: number) => void;
  updateStock: (id: string, amount: number) => void;
  deleteCategory: (id: string) => void;
}

const InventoryContext = createContext<InventoryContextType | undefined>(undefined);

export const InventoryProvider = ({ children }: { children: ReactNode }) => {
  const [categories, setCategories] = useState<ProductCategory[]>(() => {
    try {
      const saved = localStorage.getItem('inventoryCategories');
      return saved ? JSON.parse(saved, (key, value) => {
        if (key === 'createdAt' || key === 'updatedAt') {
          return new Date(value);
        }
        return value;
      }) : [];
    } catch {
      return [];
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem('inventoryCategories', JSON.stringify(categories));
    } catch (error) {
      console.error('Failed to save to localStorage:', error);
    }
  }, [categories]);

  const addCategory = (name: string, initialStock: number) => {
    if (!name.trim()) {
      toast.error('商品分类名称不能为空');
      return;
    }
    
    if (categories.some(cat => cat.name.toLowerCase() === name.toLowerCase())) {
      toast.error('该商品分类已存在');
      return;
    }
    
    const newCategory: ProductCategory = {
      id: Date.now().toString(),
      name: name.trim(),
      stock: initialStock,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    setCategories(prev => [...prev, newCategory]);
    toast.success(`已添加商品分类：${name}`);
  };

  const updateStock = (id: string, amount: number) => {
    setCategories(prev => 
      prev.map(cat => 
        cat.id === id 
          ? { 
              ...cat, 
              stock: Math.max(0, cat.stock + amount),
              updatedAt: new Date() 
            } 
          : cat
      )
    );
    toast.success('库存已更新');
  };

  const deleteCategory = (id: string) => {
    setCategories(prev => prev.filter(cat => cat.id !== id));
    toast.success('商品分类已删除');
  };

  return (
    <InventoryContext.Provider value={{ categories, addCategory, updateStock, deleteCategory }}>
      {children}
    </InventoryContext.Provider>
  );
};

export const useInventory = () => {
  const context = useContext(InventoryContext);
  if (context === undefined) {
    throw new Error('useInventory must be used within an InventoryProvider');
  }
  return context;
};